<?
require("../../common/init.php");
require("author.php");
require("upfile.php");
include(ROOT."common/class_image_resize.php");

$shipment_method=new DB(Tshipment_method,$conn);
$sales_order=new DB(Tsales_order,$conn);
$sales_order_detail=new DB(Tsales_order_detail,$conn);
$express_company=new DB(Texpress_company,$conn);
$refund = new DB(Trefund, $conn);
$refund_reason = new DB(Trefund_reason, $conn);
$customer = new DB(Tcustomer, $conn);
$coupon = new DB(Tcoupon, $conn);
$gee=$refund; // gee, 意为赶车时候喊的"驾", 此处用来表示次页面的主角对象
//$cate=$product_category; // cate = category, 分类

$filter="1";
if(isset($_GET["filter"]))$filter=clean($_GET["filter"]);
if(isset($_POST["filter"]))$filter=clean($_POST["filter"]);

switch ($filter){
    case 1:
        $title=ROOT_ORDER_REFUND_CHECKING;
        break;
    case 2:
        $title=ROOT_ORDER_REFUND_NO_CHECKED;
        break;
    case 3:
        $title=ROOT_ORDER_REFUND_REFUND;
        break;
    case 4:
        $title=ROOT_ORDER_REFUND_REFUNDED;
        break;
    default:
        $title=ROOT_ORDER_REFUND_CHECKED;
}

$url='refund';
$s=isset($_GET["s"])?clean($_GET["s"]):''; // search
$cateid=isset($_GET["cid"])?clean($_GET["cid"]):0;
$do=isset($_GET["do"])?clean($_GET["do"]):'view'; // 操作: 查看/编辑/删除
$action=isset($_POST["action"])?clean($_POST["action"]):''; // 数据库操作: CURD
$page=1; if(isset($_GET["page"]))if(is_numeric($_GET["page"]))$page=$_GET["page"]; // current page 当前页码
$id=0; if (isset($_GET["id"])) $id = clean($_GET["id"]);

// sql action / sql 动作
switch ($action){
    case "update":
        sql_update();
        break;
    case "add":
        sql_insert();
        break;
}

if($id==0){
    $order='';
    $gee->rows=15;
    $where=array();
    if($filter!=''){
        $where[]=array('name'=>'refund_status','val'=>$filter,'opn'=>'=', 'and'=>'and');
    }
    if($s!='') {
        $where[]=array('name'=>'sales_order_id','val'=>$s,'opn'=>'like', 'and'=>'and');
    }
    $pages=$gee->count_pages($where);
    $info=$gee->get_page($page,$where);
}
else $info=$gee->get_row($id);

function update($info)
{
    global $gee, $url, $h, $id;
    if($id==0)
    {
        echo "Invali argument!!!";
        exit;
    }
    echo $h->form($url.'.php', 1, '');
    show_box($info,true, false);
    echo $h->hidden('action', 'update');
    echo $h->former();
}
function delete($id)
{
    global $gee,$url;
    if($dave->delete($uid)) wheel($url.'.php');
}
function show_info()
{
    global $gee,$info,$id;
    if($id==0) show_boxes($info);
    else show_box($info, false, false);
}
function sql_update()
{
    global $product, $gee, $url, $filter, $customer, $sales_order, $coupon, $recode, $template;

    $picdir=ROOT.'upload/';
    $id=iso(@$_POST["id"]);
    $info_refund=$gee->get_row($id); // refund/订单取消
    $info = $sales_order->get_row($info_refund['sales_order_id'], 'ref_no');
    $candelete=0;
    $arr=array(
//        'shipped_time'=>iso(@$_POST["shipped_time"]),
//        'express'=>iso(@$_POST["express"]),
//        'shipment_tracking_no'=>iso(@$_POST["shipment_tracking_no"]),
        'refund_status'=>iso(@$_POST["refund_status"]),
        'operator_remark'=>iso(@$_POST["operator_remark"]),
        'updated_time'=>date('Y-m-d H:i:s', time())
    );
   /* if( isset($_FILES["cpic"]) && $_FILES["cpic"]["size"] > 0) {
        $oldcpic=$picdir.$info['receipt_doc'];
        $candelete=1;

        $pic=upfile($_FILES["cpic"]);
        $image_resize=new Image_resize($picdir.$pic,600,600,0,$picdir.$pic);
        $arr['receipt_doc']=$pic;
    }*/
//    if(isset($_POST['paid_time'])) $arr['paid_time']=$_POST['paid_time'];
//    if(isset($_POST['payer'])) $arr['payer']=$_POST['payer'];
//    if(isset($_POST['payer_id'])) $arr['payer_id']=$_POST['payer_id'];
//    if(isset($_POST['payment_ref_no'])) $arr['payment_ref_no']=$_POST['payment_ref_no'];

    if($gee->update($arr, 'id', $id)){
        if($_POST['refund_status'] == 2){
            $order_arr = array('order_status' => $info_refund['order_status']);
            $sales_order->update($order_arr, 'ref_no', $info_refund['sales_order_id']);
        }

        if($_POST['refund_status'] == 3){
            $where_r = array();
            $where_r[] = array('name'=>'template_id', 'val'=>1, 'opn'=>'=', 'and'=>'and');
            $where_r[] = array('name'=>'recode_name', 'val'=>'sales_order_id', 'opn'=>'=', 'and'=>'and');
            $where_r[] = array('name'=>'recode_value', 'val'=>$_POST['sales_order_id'], 'opn'=>'=', 'and'=>'and');
            $r = $recode->get_rows_advanced(1, $where_r);
            if(!$r){
                $wallet_arr = array(
                    'template_id' => 1,
                    'value' => $_POST['sales_order_id'],
                    'type' => 1,
                    'customer_id' => $_POST['customer_id'],
                    'user_id' => $_POST['userid'],
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'recode_name' => 'sales_order_id',
                    'recode_value' => $_POST['sales_order_id']
                );
                $recode->insert($wallet_arr);
            }else{
                $wallet_arr = array('create_time'=>date('Y-m-d H:i:s', time()));
                $recode->update($wallet_arr, 'id', $r[0]['id']);
            }
        }
        if($_POST['refund_status'] == 4){
            if($info['payment_ref_no']){
                $point = !empty($info['point_id']) ? $info['point_id'] : 0;
                $point_discount_amount = !empty($info['point_discount_amount']) ? $info['point_discount_amount'] : 0;
                $coupon_id = !empty($info['coupon_id']) ? $info['coupon_id'] : 0;
                $coupon_discount_amount = !empty($info['coupon_discount_amount']) ? $info['coupon_discount_amount'] : 0;
                $tem_point = $point - $info['total_price'] * PAY2POINT;
                $tem_total_point = 0 - $info['total_price'] * PAY2POINT;
                $customer->add('accumulated_point',$tem_total_point,'id',$info['customer_id']);
                $customer->add('usable_point',$tem_point,'id',$info['customer_id']);
                $coupon_arr = array('customer_id' => 0, 'used_time' => null, 'is_used' => 0);
                $coupon->update($coupon_arr, 'id', $coupon_id);
            }
            $where_r = array();
            $where_r[] = array('name'=>'template_id', 'val'=>2, 'opn'=>'=', 'and'=>'and');
            $where_r[] = array('name'=>'recode_name', 'val'=>'sales_order_id', 'opn'=>'=', 'and'=>'and');
            $where_r[] = array('name'=>'recode_value', 'val'=>$_POST['sales_order_id'], 'opn'=>'=', 'and'=>'and');
            $r = $recode->get_rows_advanced(1, $where_r);
            pre($r);
            $customer_info = $customer->get_row($_POST['customer_id']);
            if(!$r){
                $wallet_arr = array(
                    'template_id' => 2,
                    'value' => $_POST['sales_order_id'].'|'.$_POST['refund_reason'].'|'.$_POST['operator_remark'].'|'.$_POST['refund_amount'].'|'.$_POST['refund_account'],
                    'type' => 1,
                    'customer_id' => $_POST['customer_id'],
                    'user_id' => $_POST['userid'],
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'recode_name' => 'sales_order_id',
                    'recode_value' => $_POST['sales_order_id']
                );
                $recode->insert($wallet_arr);
                $customer_arr = array(
                    'usable_balance'=>$customer_info['usable_balance']+$_POST['refund_amount'],
                    'all_balance'=>$customer_info['all_balance']+$_POST['refund_amount'],
                );
                $customer->update($customer_arr,'id', $_POST['customer_id']);
            }else{
                $wallet_arr = array(
                    'value' => $_POST['sales_order_id'].'|'.$_POST['refund_reason'].'|'.$_POST['operator_remark'].'|'.$_POST['refund_amount'].'|'.$_POST['refund_account'],
                    'user_id' => $_POST['userid'],
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'recode_name' => 'sales_order_id',
                    'recode_value' => $_POST['sales_order_id']
                );
                $recode->update($wallet_arr, 'id', $r[0]['id']);
                $a = explode('|', $r[0]['value']);
                $customer_arr = array(
                    'usable_balance'=>$customer_info['usable_balance']+($_POST['refund_amount'] - $a[3]),
                    'all_balance'=>$customer_info['all_balance']+($_POST['refund_amount'] - $a[3]),
                );
                $customer->update($customer_arr,'id', $_POST['customer_id']);
            }
        }
        /*if($_POST['order_status'] == 5){
            if($_POST['payment_method_id'] == 5 || $_POST['payment_method_id'] == 6){
                // 加积分 add point
                $customer->add_point_by_order($arr['payment_ref_no']);
                // 更新级别
                $customer->update_grade($info['customer_id']);
            }
        }
        // 是否删除旧的收款凭据
        if($candelete)@unlink($oldcpic);*/

        // 货到付款的订单, 管理员取消后要恢复库存
        $ref_no=$info['ref_no'];
        $payment_method_id=$info['payment_method_id'];
        if($payment_method_id==5 && $arr['order_status']=='9'){
            $product->restore_stock_by_order($ref_no);
        }
        yell(ROOT_HANDLE_SUCCESS,$url.'.php'.(($filter!="")?"?page=".$page."&filter=".$filter:""));
    }
    else echo mysql_error();
}

// view 加载视图
require ROOTVIEW.$url.'.php';

// end sales_order.php
